<template>
    <div style="background-color:#f1f1f1">
        <mt-header title="秒杀">
            <router-link to="/home" slot="left">
                <mt-button icon="back">返回</mt-button>
            </router-link>
        </mt-header>
        <el-tabs v-model="activeName" @tab-click="handleClick"  style="background-color:#fff">
            <el-tab-pane label="10:00开抢" name="first"></el-tab-pane>
            <el-tab-pane label="14:00开抢" name="second"></el-tab-pane>
            <el-tab-pane label="16:00开抢" name="third"></el-tab-pane>
            <el-tab-pane label="21:00开抢" name="fourth"></el-tab-pane>
        </el-tabs>
        <div class="container">
            <p class="timer">
                <span v-if="time[0]==-1">已开抢</span>
                <span v-if="time[0]>=0">开抢倒计时<span class="cnt">{{time[0]}}</span>:<span class="cnt">{{time[1]}}</span>:<span class="cnt">{{time[2]}}</span></span>
            </p>
            <ul class="infinite-list boxContainer" v-infinite-scroll="load" style="overflow:auto" infinite-scroll-distance="10" :infinite-scroll-disabled="close[activeName]" :key="activeName">
                <div class="seckillBox infinite-list-item" v-for="(item,index) in secKillList[activeName]" :key="index">
                    <div class="imgBox"><img :src="item.shopUrl"></div>
                    <div class="messageBox">
                        <p class="shopBox">{{item.seckillName}}</p>
                        <p class="timeBox">{{item.startTime}}到{{item.endTime}}</p>
                        <p class="reductionBox">满{{item.fullReduction/100}}减{{item.reduction/100}}</p>
                        <span class="restBox">还剩{{item.redpaperNum}}份</span>
                        <span class="buttonBox" v-if="time[0]==-1" @click="doSeckill(item.redShopParperId,index)" :class="{disabled:isDisabled[item.redShopParperId]}">立即领取</span>
                        <span class="buttonBox closeButton" v-if="time[0]!=-1">尚未开始</span>
                        <span class="buttonBox closeButton" v-if="item.redpaperNum==0">已被抢完</span>
                        <span class="buttonBox closeButton" v-if="isBuyOrNotBuy(item.redShopParperId)!=-1">已经领取</span>
                    </div>
                </div>
            </ul>
        </div>
    </div>
</template>
<script>
    import Vue from 'vue'
    import { Indicator } from 'mint-ui';
    export default{
        data(){
            return{
                activeName:"first",
                openTime:null,//开启的时间
                time:[-1,-1,-1],
                clock:null,
                secKillTime:'',
                secKillList:{
                    first:[],
                    second:[],
                    third:[],
                    fourth:[]
                },
                currentPage:{
                    first:0,
                    second:0,
                    third:0,
                    fourth:0
                },
                size:5,
                close:{
                    first:false,
                    second:false,
                    third:false,
                    fourth:false
                },
                userBuy:{
                    first:null,
                    second:null,
                    third:null,
                    fourth:null
                },
                isDisabled:{}
            }
        },
        beforeRouteLeave(to, form, next) {//离开路由之前
            clearInterval(this.clock);//清除时钟
            next();
        },
        mounted(){
            this.handleClick();
        },
        methods:{
            isBuyOrNotBuy(item){
                if(this.userBuy[this.activeName]==null)
                    return -1;
                return this.userBuy[this.activeName].indexOf(item);
            },
            getuserBuy(){
                if(window.sessionStorage.getItem('tokenStr')&&this.userBuy[this.activeName]==null){
                    let postData={             	
                        killTime:this.secKillTime,
                    };
                    let tokenStr=window.sessionStorage.getItem('tokenStr');
                    this.getRequest('/seckill/seckillListbyuser',postData,tokenStr).then(response=>{
                        if(response.code==200){
                            this.userBuy[this.activeName]=response.obj;
                        }
                    })
                }
            },
            handleClick(tab,event){
                this.getTime();//计算秒杀的时间，并且进行倒计时
                this.getuserBuy();
            },
            async load(){
                this.getList(this.activeName);
            },
            async getList(index){
                this.close[index]=true;//避免重复加载
                this.currentPage[index]=this.currentPage[index]+1;
                let postData={
                    killTime:this.secKillTime,
                    currentPage:this.currentPage[index],
                    size:this.size,
                };
                await this.getRequest('/seckill/seckillList',postData,null).then(response=>{
                    if(response.code==200){
                        let list=response.obj.data;
                        for(let i=0;i<list.length;i++){
                            list[i].startTime=list[i].startTime.replace(/T/," ");
                            list[i].endTime=list[i].endTime.replace(/T/," ");
                            list[i].startTime=list[i].startTime.slice(0,16);
                            list[i].endTime=list[i].endTime.slice(0,16);
                            list[i].shopUrl="/file"+list[i].shopUrl;
                            this.secKillList[index].push(list[i]);
                        }
                        console.log(this.secKillList[index].length);
                        if(this.secKillList[index].length<response.obj.total)
                            this.close[index]=false;
                    }
                });
            },
            getSeckillResult(index,i){//如果在排队中，进行轮询
                let postData={             	
                    SeckillId:index
                };
                let tokenStr=window.sessionStorage.getItem('tokenStr');
                this.getRequest('/seckill/getSeckillResult',postData,tokenStr).then(response=>{
                    if(response.code==500){//库存不足
                        this.secKillList[this.activeName][i].redpaperNum=0;
                        Indicator.close();
                        this.$message('抱歉，已被抢完');
                    }else if(response.code==200&&response.obj==0){
                        Indicator.open({
                            text: '排队中...',
                            spinnerType: 'fading-circle'
                        });
                        setTimeout(()=>{this.getSeckillResult(index,i)},100);
                    }else if(response.code==200&&response.obj!=0){
                        this.userBuy[this.activeName].push(index);//标记已经秒杀过该物品
                        this.getRequest('/seckill/SeckillNum',postData,tokenStr).then(response=>{//获取剩余商品的数量
                            if(response.code==200){
                                this.secKillList[this.activeName][i].redpaperNum=response.obj;
                            }
                        })
                        Indicator.close();
                        this.$message({
                            message:'恭喜你，秒杀成功',
                            type:'success'
                        });
                    }
                })
            },
            async doSeckill(index,i){
                Vue.set(this.isDisabled,index,true);
                setTimeout(()=>{
                    Vue.set(this.isDisabled,index,false);
                },1000);
                if(window.sessionStorage.getItem('tokenStr')){
                    let postData={             	
                        SeckillId:index
                    };
                    let tokenStr=window.sessionStorage.getItem('tokenStr');
                    await this.getRequest('/seckill/doSeckill',postData,tokenStr).then(response=>{
                        if(response.code==200&&response.obj==0){//排队抢购
                            this.getSeckillResult(index,i);
                        }else if(response.code==500&&response.obj==500){
                            this.$message('抱歉，已被抢完');
                        }else if(response.code==500&&response.onj==100){
                            this.$message('您已经参与过该秒杀活动');
                        }
                    })
                }else{
                    this.$message({
                        message: '请先登录',
                        type: 'warning'
                    });
                }  
            },
            setSecKillTime(year,month,day,hours){
                let time=year;
                if(month<10)
                    time=time+'-0'+month;
                else time=time+"-"+month;
                if(day<10)
                    time=time+"-0"+day;
                else time=time+"-"+day;
                if(hours<10)
                    time=time+" 0"+hours+":00:00";
                else time=time+" "+hours+":00:00"
                this.secKillTime=time;
            },
            getTime(){
                clearInterval(this.clock);//清除时钟
                this.nowTime=new Date();//现在的时间
                var nowDay=this.nowTime.getDate();
                var nowMonth=this.nowTime.getMonth();
                var nowYear=this.nowTime.getFullYear();
                if(this.activeName=='first'){
                    this.openTime=new Date(nowYear,nowMonth,nowDay,10,0,0);
                    this.setSecKillTime(nowYear,nowMonth+1,nowDay,10);
                }else if(this.activeName=='second'){
                    this.openTime=new Date(nowYear,nowMonth,nowDay,14,0,0);
                    this.setSecKillTime(nowYear,nowMonth+1,nowDay,14);
                }else if(this.activeName=='third'){
                    this.openTime=new Date(nowYear,nowMonth,nowDay,16,0,0);
                    this.setSecKillTime(nowYear,nowMonth+1,nowDay,16);
                }else if(this.activeName=='fourth'){
                    this.openTime=new Date(nowYear,nowMonth,nowDay,21,0,0);
                    this.setSecKillTime(nowYear,nowMonth+1,nowDay,21);
                }
                this.clock=setInterval(()=>{
                    let nowTime=new Date();
                    let cutTime=this.openTime.getTime()-nowTime.getTime();//时间差的毫秒数
                    //计算出小时数
                    let leave1=cutTime%(24*3600*1000);//计算天数后剩余的毫秒数
                    let hours=Math.floor(leave1/(3600*1000));
                    //计算相差分数数
                    let leave2=leave1%(3600*1000);//计算小时数后剩余的毫秒数
                    let minutes=Math.floor(leave2/(60*1000));
                    //计算相差秒数
                    let leave3=leave2%(60*1000);
                    let seconds=Math.floor(leave3/1000);
                    if(hours<0||minutes<0||seconds<0){
                        clearInterval(this.clock);
                        this.time=[-1,-1,-1];
                    }else{
                        if(hours<10)
                            hours='0'+hours;
                        if(minutes<10)
                            minutes='0'+minutes;
                        if(seconds<10)
                            seconds='0'+seconds;
                        this.time=[hours,minutes,seconds];
                    }
                },1000);
            }
        }
    }
</script>
<style lang="scss" scoped>
    @import 'mint-ui/lib/style.css';
    @import '../style/mixin';
    *{
        margin: 0;
        padding: 0;
    }
    .disabled{
        pointer-events: none;
    }
    /deep/ .el-tabs__item{
        font-size:18px;
    }
    /deep/ .el-tabs__header{
        margin:0;
    }
    /deep/ .el-tabs__nav{
        padding:0.2rem;
    }
    .container{
        @include white;
        .timer{
            @include width-height(100%,2.5rem);
            line-height: 2.5rem;
            text-align: right;
            span{
                padding-right: 1rem;
            }
            .cnt{
                margin:0 0.2rem 0 0.2rem;
                border:1px solid black;
                padding: 0 0.2rem 0 0.2rem;
                @include font-size-color(1rem,#f00);
            }
        }
        .boxContainer{
            @include width-height(100%,83vh);
        }
        .seckillBox{
            background-color: #fff;
            @include width-height(100%,6rem);
            padding:0.5rem 0 0.2rem 0;
            border:1px solid #f1f1f1;
            display: grid;
            grid-template-columns: 15% 85%;
            grid-template-rows: 70% 30;
            margin-bottom: 0.3rem;
            border-radius: 1rem;
            .imgBox{
                padding-left: 0.5rem;
                img{
                    @include width-height(50px,50px);
                    border-radius: 0.5rem;
                }
            }
            .messageBox{
                position: relative;
                .shopBox{
                    @include font-size-color(1.2rem,#000);
                    font-weight: bold;
                }
                .timeBox{
                    @include font-size-color(1rem,#666);
                }
                .reductionBox{
                    @include font-size-color(1.2rem,rgba(231, 73, 25, 0.87));
                }
                .restBox{
                    @include font-size-color(1rem,#666);
                }
                .buttonBox{
                    display: inline-block;
                    @include font-size-color(1rem,#fff);
                    background-color: rgba(231, 73, 25, 0.87);
                    @include width-height(4rem,1.5rem);
                    padding: 0.3rem;
                    position: absolute;
                    right: 0.5rem;
                    bottom: 0.3rem;
                    border-radius: 0.5rem;
                }
                .closeButton{
                    background-color: #999;
                }
            }
        }
    }
</style>
